package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserRoleConstants;
import com.ruoyi.common.cont.SysConst;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.valid.VEdit;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    /**
     * 获取全部用户列表（带分页）
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 机构用户列表查询(纯列表)
     */
    @PostMapping("/listAll")
    public AjaxResult listAll(@RequestBody SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        return AjaxResult.success(list);
    }

    /**
     * 获取机构用户分页
     */
    @PreAuthorize("@ss.hasPermi('system:user:page')")
    @PostMapping("/page")
    public TableDataInfo page(@RequestBody SysUser user)
    {
        startPageBody(user);
        List<SysUser> list = userService.selectInsUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取企业用户分页
     */
    @PreAuthorize("@ss.hasPermi('system:user:page')")
    @PostMapping("/pageEntUser")
    public TableDataInfo pageEntUser(@RequestBody SysUser user)
    {
        startPageBody(user);
        List<SysUser> list = userService.selectEntUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        Long userId = getUserId();
        String message = userService.importUser(userList, updateSupport, userId);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        //构建选择框
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        //构建用户信息
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 校验是否重复
     * false 重复 true不重复
     */
    @PostMapping("/verify")
    public AjaxResult verifyRepeat(@RequestBody SysUser user)
    {
        return AjaxResult.success(userService.verifyRepeatData(user));
    }

    /**
     * 新增机构/协会 用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "新增机构用户", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        String message = userService.checkUserInfo(user);
        if (StringUtils.isNotEmpty(message)) {
            return error(message);
        }
        user = userService.createInsUserInfo(user);
        user.setCreateBy(getUserId());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 新增管理员 用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "新增管理员", businessType = BusinessType.INSERT)
    @PostMapping("/manager")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addManager(@RequestBody SysUser user)
    {
        user.setTypeCode(UserRoleConstants.UserRoleCode.ADMIN.getCode());
        String message = userService.checkUserInfo(user);
        if (StringUtils.isNotEmpty(message)) {
            return error(message);
        }
        user = userService.createManagerUserInfo(user);
        user.setCreateBy(getUserId());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 新增企业 用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "新增企业用户", businessType = BusinessType.INSERT)
    @PostMapping("/addEnt")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addEnt(@RequestBody SysUser user)
    {
        //检查数据正确性
        String s = userService.checkEntUserInfo(user, SysConst.OPERATE.SAVE.getCode());
        if (s != null) {
            return error(s);
        }
        //先按照规则生成企业账号信息
        user = userService.createEntUserInfo(SecurityUtils.getUserId(), user);
        user.setCreateBy(getUserId());
        return userService.insertUser(user) > 0 ? AjaxResult.success(user) : AjaxResult.error();
    }

    /**
     * 修改机构用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "修改机构用户", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@Validated(VEdit.class) @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        String message = userService.checkUserInfo(user);
        if (StringUtils.isNotEmpty(message)) {
            return error(message);
        }
        user.setUpdateBy(getUserId());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 修改企业用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "修改企业用户", businessType = BusinessType.UPDATE)
    @PutMapping("/editEntUser")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editEntUser(@Validated(VEdit.class) @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkParam(user);
        String s = userService.checkEntUserInfo(user, SysConst.OPERATE.UPDATE.getCode());
        if (s != null) {
            return error(s);
        }
        //判断是否有权限操作
        userService.checkEditEntUserAuth(user, SecurityUtils.getTypeCode(), SecurityUtils.getUserId());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 用户启用禁用
     */
    @PreAuthorize("@ss.hasPermi('system:user:enable')")
    @Log(title = "用户启用禁用", businessType = BusinessType.UPDATE)
    @PostMapping("/enable")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult enable(@RequestBody SysUser user)
    {
        boolean flag = userService.enableUser(user);
        return flag ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/rePassword")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult rePassword(@RequestBody SysUser user)
    {
        //超级管理员不允许重置
        userService.checkUserAllowed(user);
        boolean flag = userService.rePassword(user);
        return flag ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 查看密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:viewPwd')")
    @Log(title = "查看密码", businessType = BusinessType.OTHER)
    @PostMapping("/view/password")
    public AjaxResult viewPassword(@RequestBody SysUser user)
    {
        //超级管理员不允许查看
        userService.checkUserAllowed(user);
        String password = userService.viewPassword(user);
        return AjaxResult.success(password);
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUserId());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUserId());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 获取机构-企业树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PostMapping("/userTree")
    public AjaxResult userTree(@RequestBody SysUser sysUser)
    {
        List<SysUser> userTreeList = userService.selectUserTreeList(sysUser);
        return success(userTreeList);
    }

}
